<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-row>
        <el-col :span="4.1">
          <el-form-item label="药师名字" prop="signer">
            <el-input
              v-model="queryParams.signer"
              placeholder="请输入药师名字"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="时间">
            <el-date-picker
              v-model="time"
              type="daterange"
              range-separator="至"
              start-placeholder="请选择开始日期"
              end-placeholder="请选择结束日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              @change="handletime"
              clearable
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3.9" style="">
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索
            </el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置
            </el-button
            >
            <el-button
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['workstation:statistics:workload:export']"
            >下载表格(导出Excel)
            </el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      v-loading="loading"
      :data="baseInfoList"
      border=""
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" type="index" align="center" width="50">
      </el-table-column>
      <el-table-column label="药师名字" align="center" prop="signer"/>
      <el-table-column label="科室/病区" align="center" prop="deptName"/>
      <el-table-column
        label="药历数"
        align="center"
        prop="totalCount"
        sortable
      />

      <el-table-column
        label="住院天数"
        align="center"
        prop="totalDays"
        sortable
      />

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改患者基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="85px"
        label-position="left"
      >
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名"/>
        </el-form-item>
        <el-form-item label="ID号" prop="patientNo">
          <el-input v-model="form.patientNo" placeholder="请输入ID号"/>
        </el-form-item>
        <el-form-item label="科室/病区" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择科室/病区"
          />
        </el-form-item>
        <el-form-item label="入院时间" prop="admissionTime">
          <el-date-picker
            clearable
            v-model="form.admissionTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择入院时间"
            :picker-options="setDisabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="住院医师" prop="doctorId">
          <el-select
            v-model="form.doctorId"
            placeholder="请选择临床药师"
            clearable
            @change="handleDoctorName"
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in DoctorList"
              :key="index"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="床号" prop="bedNo">
          <el-input v-model="form.bedNo" placeholder="请输入床号"/>
        </el-form-item>
        <el-form-item label="第一诊断" prop="firstDiagnose">
          <el-input v-model="form.firstDiagnose" placeholder="请输入第一诊断"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
        >确 定
        </el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {workload} from "@/api/tongjiguanli/index.js";
import {
  addBaseInfo,
  updateBaseInfo,
} from "@/api/workstation/baseInfo";
import {deptTreeSelect, deptList} from "@/api/system/user";

export default {
  name: "tongji",
  data() {
    return {
      downAllyaoLiXiaoLoading: false, // 下载按钮加载状态
      setDisabled: {
        // 返回禁用时间
        disabledDate(time) {
          return time.getTime() > Date.now(); // 可选历史天、可选当前天、不可选未来天
        },
      },
      // 部门树选项
      deptOptions: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者基本信息表格数据
      baseInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        doctorName: undefined,
        signer: undefined, // 住院医师的名字  搜索
        medicareNo: undefined,
        patientName: undefined,
        // medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        // admissionDate: undefined,
        admissionTime: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        nickName: undefined, // 昵称
        dischargeTime: undefined, // 出院时间
        "params[beginAge]": undefined, // 年龄开始
        "params[endAge]": undefined, // 年龄结束
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{required: true, message: "患者ID不能为空", trigger: "blur"}],
        patientName: [
          {required: true, message: "患者姓名不能为空", trigger: "blur"},
        ],
        medicalRecordNo: [
          {required: true, message: "病案号不能为空", trigger: "blur"},
        ],
        patientNo: [
          {required: true, message: "ID号不能为空", trigger: "blur"},
        ],
        deptId: [
          {required: true, message: "科室/病区不能为空", trigger: "blur"},
        ],
        admissionTime: [
          {required: true, message: "入院时间不能为空", trigger: "blur"},
        ],
        doctorId: [
          {required: true, message: "临床药师不能为空", trigger: "blur"},
        ],
        bedNo: [{required: true, message: "床号不能为空", trigger: "blur"}],
        firstDiagnose: [
          {required: true, message: "第一诊断不能为空", trigger: "blur"},
        ],
        guardianLevel: [
          {required: true, message: "监护分级不能为空", trigger: "blur"},
        ],
        patientState: [
          {required: true, message: "住院状态不能为空", trigger: "blur"},
        ],
        patientSex: [
          {required: true, message: "患者性别不能为空", trigger: "change"},
        ],
        patientAge: [
          {required: true, message: "年龄不能为空", trigger: "blur"},
        ],
        patientProfession: [
          {required: true, message: "职业不能为空", trigger: "blur"},
        ],
        nation: [{required: true, message: "民族不能为空", trigger: "blur"}],
        patientHeight: [
          {required: true, message: "身高不能为空", trigger: "blur"},
        ],
        patientWeight: [
          {required: true, message: "体重不能为空", trigger: "blur"},
        ],
        patientBmi: [
          {required: true, message: "BMI不能为空", trigger: "blur"},
        ],
        phoneNo: [
          {required: true, message: "联系方式不能为空", trigger: "blur"},
        ],
        payWay: [
          {required: true, message: "付费方式不能为空", trigger: "blur"},
        ],
        sourceInfo: [
          {required: true, message: "数据来源不能为空", trigger: "blur"},
        ],
      },
      guardianLevel: [], // 监护分级
      patientState: [], // 住院状态
      userSex: [], // 患者性别
      payWay: [], // 付费方式
      sourceInfo: [], // 患者信息来源
      DoctorList: [], // 对应科室的医生列表
      msg: {}, // 患者管理页搜索条件
      time: "", // 起始日期
      errormsg: "",
      errormsg2: "",
    };
  },
  computed: {
    role() {
      return this.$store.state.user.roles;
    },
    useInfo() {
      return this.$store.state.user.user;
    },
    info() {
      return this.$store.state.user.search;
    },
  },
  created() {
    this.getList();
  },
  methods: {
    handletime(val) {
      if (val) {
        this.queryParams["params[beginDate]"] = val[0];
        this.queryParams["params[endDate]"] = val[1];
      } else {
        this.queryParams["params[beginDate]"] = "";
        this.queryParams["params[endDate]"] = "";
      }
    },
    // 去患者详情页
    toUseDetail(item) {
      this.$store.commit("SET_SEARCH", this.queryParams);
      // 打开新窗口
      window.open(
        `/detail?id=${item.id}&medicalRecodeNo=${item.medicalRecordNo}`
      );
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      // 质控员 拥有所有科室
      if (this.role.includes("quality")) {
        deptTreeSelect().then((response) => {
          this.deptOptions = response.data;
        });
        return;
      }
      // 指定了常驻病区 下拉查询
      if (this.useInfo.longDept) {
        let params = {};
        params.params = {};
        params.params["longDept"] = this.useInfo.longDept;
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = [];
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId,
            };
            arr.push(obj);
          });
          this.deptOptions = arr;
        });
      } else {
        // 指定了科室  没有指定病区
        let params = {
          parentId: this.useInfo.deptId,
        };
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = [];
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId,
            };
            arr.push(obj);
          });
          this.deptOptions = arr;
        });
      }
    },
    /** 查询患者基本信息列表 */
    getList() {
      this.loading = true;
      workload(this.queryParams).then((response) => {
        this.baseInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        patientName: undefined,
        medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        admissionDate: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        patientName: undefined,
        medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        // admissionDate: undefined,
        admissionTime: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        nickName: undefined,
        "params[beginDate]": undefined,
        "params[endDate]": undefined,
      };
      this.time = "";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 查看按钮操作
    handleLook(row) {
      // 打开新窗口
      window.open(
        `/medicine?id=${row.id}&medicalRecordNo=${row.medicalRecordNo}`
      );
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加患者基本信息";
    },
    handleDoctorName(val) {
      let person = this.DoctorList.filter((item) => {
        return item.userId == val;
      });
      this.form.doctorName = person[0].nickName;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 打开新窗口
      window.open(
        `/medicine?id=${row.id}&medicalRecordNo=${row.medicalRecordNo}`
      );
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            this.form.sourceInfo = "0"; // 代表是手工录入
            addBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除 " + row.patientName + " 的数据项？")
        .then(() => {
          this.loading = true;
          return remove(row.medicalRecordNo);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 下载药历
    downyaoLi(row) {
      this.downAllyaoLiXiaoLoading = true;
      this.$download.get(
        "/workstation/medicationRecord/overall/",
        row.medicalRecordNo,
        `${row.patientName}.docx`
      );
      this.downAllyaoLiXiaoLoading = false;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "workstation/statistics/workload/export",
        {
          ...this.queryParams,
        },
        `工作量统计.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss"></style>
